package com.german.numbers;

import java.util.ArrayList;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class learn extends Activity  implements OnClickListener {
    /** Called when the activity is first created. */
    String correctAnswerNumber = "";
	String currentCorrectAnswer="";
    ArrayList<String> currentExpression = null;
    CountDownTimer timer;
    AlertDialog.Builder builder;
    
    final Integer[] levelPoints = {10,10,10,10};
    final Integer[] secToThink = {5,10,15,20};
    final Integer maxLevel = 4;
    Integer currentLevel = 0;
    Integer wordCount = 0;
    Integer points = 0;
    boolean gameFinished = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStartView();
    }
    
    private void setAboutView(){
    	setContentView(R.layout.about);
    	Button backInMainMenu = (Button) findViewById(R.id.about_backInMenu);
    	backInMainMenu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        		if(timer!=null)
        			timer.cancel();
            	setStartView();
            }
        });
    }
    
    private void setHowToView(){
    	setContentView(R.layout.howto);
    	Button backInMainMenu = (Button) findViewById(R.id.howto_backInMenu);
    	backInMainMenu.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        		if(timer!=null)
        			timer.cancel();
            	setStartView();
            }
        });
    }
    
    private void setStartView(){
    	setContentView(R.layout.start);
    	Button startLevel0 = (Button) findViewById(R.id.start_startLearn0);
    	Button startLevel1 = (Button) findViewById(R.id.start_startLearn1);
    	Button startLevel2 = (Button) findViewById(R.id.start_startLearn2);
    	Button startLevel3 = (Button) findViewById(R.id.start_startLearn3);
    	Button howto = (Button) findViewById(R.id.start_howToPlay);
    	Button about = (Button) findViewById(R.id.start_about);
    	Button exit = (Button) findViewById(R.id.start_exit);
    	
    	startLevel0.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	gameFinished = false;
        	currentLevel=0;
            	 wordCount = 0;
            	 points = 0;
            	 setMainView();
     			if(!gameFinished)
     				setNewExpression();
             }
         });
    	startLevel1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            gameFinished = false; 
            currentLevel=1;
           	wordCount = 0;
           	points = 0;
           	setMainView();
			if(!gameFinished)
				setNewExpression();
            }
        });
    	startLevel2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            gameFinished = false;
            currentLevel=2;
           	wordCount = 0;
           	points = 0;
           	setMainView();
 			if(!gameFinished)
				setNewExpression();
            }
        });
    	startLevel3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            gameFinished = false;
            currentLevel=3;
           	wordCount = 0;
           	points = 0;
           	setMainView();
 			if(!gameFinished)
				setNewExpression();
            }
        });
    	builder = new AlertDialog.Builder(this);
    	exit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
	            	builder.setMessage("Are you sure you want to exit?")
	                .setCancelable(false)
	                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int id) {
	                         learn.this.finish();
	                    }
	                })
	                .setNegativeButton("No", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int id) {
	                         dialog.cancel();
	                    }
	                });
            		AlertDialog alert = builder.create();
            		alert.show();
            }
        });
    	
    	about.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	setAboutView();
            }
        });
    	
    	howto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	setHowToView();
            }
        });
    
    }
    
    private void setMainView(){
    	setContentView(R.layout.main);
    	updateMainView();
    }
        
    private void updateMainView(){
    	Button possible1 = (Button) findViewById(R.id.main_possible1);
    	Button possible2 = (Button) findViewById(R.id.main_possible2);
    	Button possible3 = (Button) findViewById(R.id.main_possible3);
    	Button possible4 = (Button) findViewById(R.id.main_possible4);
    	Button backInMenu = (Button) findViewById(R.id.main_backInMenu);
        TextView currentScore = (TextView) findViewById(R.id.main_currentScore);
     	TextView level = (TextView) findViewById(R.id.main_level);
     	TextView nextLevel = (TextView) findViewById(R.id.main_nextLevel);
      	ProgressBar scoresProgress =  (ProgressBar) findViewById(R.id.main_scoresProgress);
     	
         possible1.setOnClickListener(this);
         possible2.setOnClickListener(this);
         possible3.setOnClickListener(this);
         possible4.setOnClickListener(this);
         backInMenu.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
         		if(timer!=null)
        			timer.cancel();
         		stopLearning();
             }
         });
         
     	level.setText(this.currentLevel.toString());
    	currentScore.setText(this.points.toString());
    	nextLevel.setText(this.levelPoints[this.currentLevel].toString());
    	scoresProgress.setMax(this.levelPoints[this.currentLevel]);
    	scoresProgress.setProgress(points);
    }
    
    private void setErrorView(){
    	setContentView(R.layout.mistake);
    	Button continueTraining = (Button) findViewById(R.id.mistake_continueTraining);
        TextView number1 = (TextView) findViewById(R.id.mistake_number1);
        TextView number2 = (TextView) findViewById(R.id.mistake_number2);
        TextView answer = (TextView) findViewById(R.id.mistake_answer);
        TextView translationNumber1 = (TextView) findViewById(R.id.mistake_translationNumber1);
        TextView translationNumber2 = (TextView) findViewById(R.id.mistake_translationNumber2);
        TextView translationAnswer = (TextView) findViewById(R.id.mistake_translationAnswer);
        TextView wholeExpression = (TextView) findViewById(R.id.mistake_wholeExpression);
        
        number1.setText(currentExpression.get(1));
        number2.setText(currentExpression.get(2));
        answer.setText(this.correctAnswerNumber);
        
        String[] numbers = getResources().getStringArray(R.array.textNumbers);
        int n1 = Integer.parseInt(currentExpression.get(1));
        int n2 = Integer.parseInt(currentExpression.get(2));
        
        translationNumber1.setText(numbers[n1]);
        translationNumber2.setText(numbers[n2]);
        translationAnswer.setText(currentCorrectAnswer);
        
        wholeExpression.setText(numbers[n1]+" "+currentExpression.get(0)+" "+numbers[n2] + " = " + currentCorrectAnswer);
        
        continueTraining.setOnClickListener(this);

    }
	
    private void setNewExpression(){
    	wordCount++;
    	String[] numbers = getResources().getStringArray(R.array.textNumbers);
    	
    	TextView number1 = (TextView) findViewById(R.id.main_number1);
    	TextView number2 = (TextView) findViewById(R.id.main_number2);
    	TextView operation = (TextView) findViewById(R.id.main_operation);
    	Button possible1 = (Button) findViewById(R.id.main_possible1);
    	Button possible2 = (Button) findViewById(R.id.main_possible2);
    	Button possible3 = (Button) findViewById(R.id.main_possible3);
    	Button possible4 = (Button) findViewById(R.id.main_possible4);
   
    	if(timer!=null)
    		timer.cancel();
        Expression expression = new Expression();
        expression.setLevel(currentLevel);
        ArrayList<String> newExpression = expression.getExpression();
        this.currentExpression = newExpression;
        
        int n1 = Integer.parseInt(newExpression.get(1));
        int n2 = Integer.parseInt(newExpression.get(2));
        int c = Integer.parseInt(newExpression.get(3));
        
        
        number1.setText(numbers[n1]);
        number2.setText(numbers[n2]);
        operation.setText(newExpression.get(0));

        this.correctAnswerNumber = newExpression.get(3);
        this.currentCorrectAnswer = numbers[c];
        
        /*
         * Put correct answer on random position
         */
        Random rand = new Random();
        int correct = rand.nextInt(4);
        String rightAnswer = newExpression.get(3);
        newExpression.set(3, newExpression.get(correct+3));
        newExpression.set(correct+3, rightAnswer);
        
        /*
         * set values to the buttons
         */
        int p1 = Integer.parseInt(newExpression.get(3));
        int p2 = Integer.parseInt(newExpression.get(4));
        int p3 = Integer.parseInt(newExpression.get(5));
        int p4 = Integer.parseInt(newExpression.get(6));

        
        possible1.setText(numbers[p1]);
        possible2.setText(numbers[p2]);
        possible3.setText(numbers[p3]);
        possible4.setText(numbers[p4]);
        
        timer = new CountDownTimer(this.secToThink[this.currentLevel]*1000, 1000) {
        	public int wordNumber = wordCount;
        	public void onTick(long millisUntilFinished) {
        		if(wordCount == wordNumber){
        			TextView timeLeft = (TextView) findViewById(R.id.main_timeLeft);
        			timeLeft.setText(Integer.toString(((int)millisUntilFinished/1000)));
        		}
        	}
        	public void onFinish() {
        		if(wordCount == wordNumber){
        			setErrorView();
        		}
        		
        	}
        	};
        timer.start();
    }
    
    private void increasePoints(){
    	this.points+=(this.currentLevel+1);
    	if(this.points>=this.levelPoints[this.currentLevel]){
    		this.currentLevel++;
    		this.points = 0;
    	}
    	if(this.currentLevel == this.maxLevel){
    		this.wordCount = 0;
    		this.points = 0;
    		this.currentLevel = 0;
    		stopLearning();
    		return;
    	}
   	
    }
    
    private void decreasePoints(){
   	this.points-=(this.currentLevel+1);
    	if(this.points<0)
    		this.points=0;

    }

    private void stopLearning(){
    	this.gameFinished = true;
    	setStartView();
   }
    
	@Override
	public void onClick(View v) {
    	Button continueTraining = (Button) findViewById(R.id.mistake_continueTraining);
		if(timer!=null)
			timer.cancel();
		Button clickedButton = (Button) v;
		if (clickedButton.equals(continueTraining)){
		    decreasePoints();
			setMainView();
		    setNewExpression();
		}
		else
		{
			if(clickedButton.getText().equals(this.currentCorrectAnswer)){
				increasePoints();
				if(!this.gameFinished){
					setMainView();
					setNewExpression();
				}
			}
			else{
				setErrorView();
			}

		}
	}
}